<template>
  <!-- 搜索 -->
  <ContentWrap :show-border="false">
    <SearchBox
      :queryForm="searchList"
      :showExpland="true"
      @changeVal="handleChange"
      @query="handleSearchQuery"
      @update:exportData="handleExport"
    />
  </ContentWrap>
  <!-- 筛选 订单状态 -->
  <ContentWrap :show-border="false" :bodyStyle="{ padding: '0 10px' }">
    <OrderStatusMenu
      :list="orderStatusList"
      @tabChange="handleOrderStatus"
      :curStatus="queryParams.status"
    />
  </ContentWrap>
  <!-- 批量操作 -->
  <ContentWrap :show-border="false" :bodyStyle="{ padding: '0 10px 10px 0' }">
    <BatchAction
      ref="batchActionRef"
      :total="total"
      :sort="orderSortType"
      :selectedRows="selectedRows"
      :status="queryParams.status"
      :mode="curMode"
      @updateList="getList"
      @updateSort="updateSortType"
    />
  </ContentWrap>
  <!-- 搜索 -->
  <ContentWrap :show-border="false">
    <OrderTable
      ref="orderTableRef"
      :list="list"
      :pickUpStoreList="pickUpStoreList"
      :status="queryParams.status"
      @updateList="getList"
      @selectionChange="handleSelectionChange"
      @showActionDialog="showActionDialog"
      @updateOrderStatus="updateOrderStatus"
      @clearSelect="clearAuditSelect"
    />
    <Pagination
      v-model:limit="queryParams.pageSize"
      v-model:page="queryParams.pageNo"
      :total="total"
      @pagination="getList"
    />
  </ContentWrap>
  <ExportDrawer ref="exportDrawerRef" :selectedRows="selectedRows" />
</template>

<script lang="ts" setup>
import type { FormInstance } from 'element-plus'
import { getSimpleDeptList } from '@/api/system/dept'
import { getUserPage } from '@/api/system/user'
import { getUserPageNew } from '@/api/member/user'
import { getGlobeState } from '@/api/publicInterf'
import OrderDeliveryForm from '@/views/trade/order/form/OrderDeliveryForm.vue'
import OrderUpdateRemarkForm from '@/views/trade/order/form/OrderUpdateRemarkForm.vue'
import * as TradeOrderApi from '@/api/mall/trade/order'
import * as PickUpStoreApi from '@/api/mall/trade/delivery/pickUpStore'
import { DICT_TYPE, getIntDictOptions, getStrDictOptions } from '@/utils/dict'
import * as DeliveryExpressApi from '@/api/mall/trade/delivery/express'
import { DeliveryTypeEnum, TradeOrderStatusEnum } from '@/utils/constants'
import { OrderTableColumn, BatchAction } from './components'
import OrderStatusMenu from '@/views/trade/components/OrderStatusMenu.vue'
import type { TradeOrderQueryVO } from '@/api/mall/trade/order'

import OrderTable from './components/OrderTable.vue'

import ExportDrawer from './components/ExportDrawer.vue'

import { buildTree, deepCopy } from '@/utils/index'
import { usePageLoading } from '@/hooks/web/usePageLoading'
import download from '@/utils/download'
import { useRoute, useRouter } from 'vue-router'

const route = useRoute() // 路由
const router = useRouter() // 路由


const curStatus = route.query.status;




// const { loadStart, loadDone } = usePageLoading()

const message = useMessage() // 消息弹窗

type SortType = 'DESC' | 'ASC'

const props = defineProps({
  status: {
    type: Number,
    default: 0
  }
})

const depatList = ref([])

const createNameList = ref([])

const areaList = ref([])

const createList = ref([])

const selectedRows = ref<any[]>([])

const orderTableRef = ref<InstanceType<typeof OrderTable>>()

const exportDrawerRef = ref<InstanceType<typeof ExportDrawer>>()

const batchActionRef = ref()

const curMode = ref('batch')

const searchInitList = ref<TradeOrderQueryVO[]>([
  {
    label: '订单编号',
    code: 'orderNo',
    type: 'input'
  },

  {
    label: '地区',
    code: 'areaId',
    type: 'select',
    options: areaList.value
  },
  {
    label: '下单日期',
    code: 'orderTime',
    type: 'dateRange'
  },
  {
    label: '商品信息',
    code: 'product',
    type: 'input',
    placeHolder: '商品名称/商品ID/sku'
  },
  
  {
    label: '下单链接',
    code: 'orderLink',
    type: 'input'
  },
  // {
  //   label: '物流单号',
  //   code: 'no ',
  //   type: 'input'
  // },
  {
    label: '归属部门',
    code: 'deptId',
    type: 'treeSelect',
    options: depatList.value
  },
  {
    label: '归属人员',
    code: 'userId',
    type: 'select',
    options: createList.value
  },
  
  {
    label: 'IP',
    code: 'ipAddress',
    type: 'input'
  },
  {
    label: '留言/备注',
    code: 'message',
    type: 'input'
  },
  // {
  //   label: '订单状态',
  //   code: 'status',
  //   type: 'select',
  //   options: getIntDictOptions(DICT_TYPE.ORDER_STATUS)
  // },
  // {
  //   label: '是否有物流单',
  //   code: 'status',
  //   type: 'select',
  //   options: []
  // },
  // {
  //   label: '是否推物流',
  //   code: 'dept',
  //   type: 'select',
  //   options: [
  //     {
  //       label: '中国',
  //       value: 'CN'
  //     },
  //     {
  //       label: '美国',
  //       value: 'US'
  //     }
  //   ]
  // },
  // {
  //   label: '物流状态',
  //   code: 'dept',
  //   type: 'select',
  //   options: [
  //     {
  //       label: '中国',
  //       value: 'CN'
  //     },
  //     {
  //       label: '美国',
  //       value: 'US'
  //     }
  //   ]
  // },
  {
    label: '内部编码',
    code: 'code',
    type: 'input'
  },
  // {
  //   label: '支付方式 ',
  //   code: 'paymentMethod',
  //   type: 'select',
  //   options: [
  //     {
  //       label: '货到付款',
  //       value: 1
  //     },
  //     {
  //       label: '在线支付',
  //       value: 2
  //     }
  //   ]
  // },
  {
    label: '有无审核建议',
    code: 'suggetFlag',
    type: 'select',
    options: [
      {
        label: '有',
        value: true
      },
      {
        label: '无',
        value: false
      }
    ]
  },
    {
    label: '审核建议',
    code: 'auditSugget',
    type: 'select',
    options:getStrDictOptions(DICT_TYPE.ORDER_AUDIT_SUGGEST),
  },
  {
    label: '有无留言',
    code: 'messageFlag',
    type: 'select',
    options: [
      {
        label: '有',
        value: true
      },
      {
        label: '无',
        value: false
      }
    ]
  },
  {
    label: '下单信息',
    code: 'orderInformation',
    type: 'input'
  },
  {
    label: '订单来源',
    code: 'source',
    type: 'select',
    options:  getIntDictOptions(DICT_TYPE.ORDER_ORDER_SOURCE),
  },
  {
    label: '是否有效订单',
    code: 'validFlag',
    type: 'select',
    options: [
      {
        label: '有效',
        value: true
      },
      {
        label: '无效',
        value: false
      }
    ]
  },
  {
    label: '未签收原因',
    code: 'unsignedReason',
    type: 'select',
    options: [
      {
        label: '拒收',
        value: '拒收'
      },
      {
        label: '退货',
        value: '退货'
      }
    ]
  },
  {
    label: '异常原因',
    code: 'abnormal',
    type: 'select',
    options: getIntDictOptions(DICT_TYPE.ORDER_ABNORMAL_CAUSES),
  },
  {
    label: '无效原因',
    code: 'invalid',
    type: 'select',
    options: getIntDictOptions(DICT_TYPE.ORDER_INVALID_REASON)
  },
  // {
  //   label: '支付单号',
  //   code: 'no',
  //   type: 'input'
  // }
])

const searchList = ref(deepCopy(searchInitList.value)) 

const initOrderStatusList =ref( 
  [
  {
    label: '全部订单',
    value: 0
  },
  {
    label: '待审核',
    value: 1
  },
  {
    label: '待确认',
    value: 2
  },
  {
    label: '待发货',
    value: 3
  },
  {
    label: '缺货中',
    value: 4
  },
  {
    label: '已发货',
    value: 5
  },
  {
    label: '已签收',
    value: 6
  },
  {
    label: '未签收',
    value: 7
  },
  {
    label: '异常订单',
    value: 8
  },
  {
    label: '无效订单',
    value: 9
  }
])


const orderStatusList =ref( 
  deepCopy(initOrderStatusList.value)
)

const handleSearchQuery = (val) => {
  /***
   * 搜索框查询条件，目前考虑在查询时 queryParams = {...val,pageNo:1,pageSize:10}
   * */
   if (val.orderTime && val.orderTime.length) {
    val.startDate = val.orderTime[0]
    val.endDate = val.orderTime[1]
  }
  delete val.orderTime
  queryParams.value = {
    ...initQueryParams,
    status: queryParams.value.status,
    ...val
  }
  getList()
}

defineOptions({ name: 'TradeOrder' })

const orderSortType = ref<SortType>('DESC') // 排序方式

const { currentRoute, push } = useRouter() // 路由跳转
const loading = ref(true) // 列表的加载中
const total = ref(0) // 列表的总页数
const list = ref<TradeOrderApi.OrderVO[]>([]) // 列表的数据
const queryFormRef = ref<FormInstance>() // 搜索的表单

const initQueryParams = {
  pageNo: 1, // 页数
  pageSize: 10, // 每页显示数量
  status:  0, // 订单状态
  // payChannelCode: undefined, // 支付方式
  // createTime: undefined, // 创建时间
  // terminal: undefined, // 订单来源
  // type: undefined, // 订单类型
  // deliveryType: undefined, // 配送方式
  // logisticsId: undefined, // 快递公司
  // pickUpStoreId: undefined, // 自提门店
  // pickUpVerifyCode: undefined // 自提核销码
  areaId: undefined, // 地区id
  deptId: undefined, // 部门id
  userId: undefined, // 用户id
  ipAddress: undefined, // 用户ip
  product: undefined, // 商品信息
  orderLink: undefined, // 下单链接
  messsage: undefined, // 订单备注
  code: undefined, // 内部编码
  paymentMethod: undefined, // 支付方式
  sort: 'DESC' as SortType
}

// 表单搜索
const queryParams = ref({
  ...initQueryParams,
  status: Number( props.status || curStatus || 0)
})
const queryType = reactive({ queryParam: '' }) // 订单搜索类型 queryParam

// 订单聚合搜索 select 类型配置（动态搜索）
const dynamicSearchList = ref([
  { value: 'no', label: '订单号' },
  { value: 'userId', label: '用户UID' },
  { value: 'userNickname', label: '用户昵称' },
  { value: 'userMobile', label: '用户电话' }
])
/**
 * 聚合搜索切换查询对象时触发
 * @param val
 */
const inputChangeSelect = (val: string) => {
  dynamicSearchList.value
    .filter((item) => item.value !== val)
    ?.forEach((item1) => {
      // 清除集合搜索无用属性
      if (queryParams.value.hasOwnProperty(item1.value)) {
        delete queryParams.value[item1.value]
      }
    })
}

const handleChange = (val) => {
 
  if (val.form.deptId) {
    queryParams.value.deptId = val.form.deptId
  }

}
watch(
  () => queryParams.value.deptId,
  () => {
    getCreateNameList()
  }
)
//查询部门人员
const getCreateNameList = async () => {
  const res = await getUserPageNew({ pageNo: 1, pageSize: 99, deptId: queryParams.value.deptId })
  createNameList.value = res.map((item) => {
    return {
      label: item.nickname,
      value: item.id
    }
  })
  searchList.value.map((item) => {
    if (item.code === 'userId') {
      item.options = createNameList.value
    }
  })
}
const getStatusAccount = async () =>{
  const res = await TradeOrderApi.getAllOrderNum()
  orderStatusList.value = deepCopy(initOrderStatusList.value).map((item)=>{
    if(item.value === 0 ){
      item.label += `(${res.allCount})`
    }else if(item.value === 1 ){
      item.label += `(${res.pendingReviewCount})`
    }else if(item.value === 2 ){
      item.label += `(${res.pendingConfirmationCount})`
    }else if(item.value === 3 ){
      item.label += `(${res.pendingShipmentCount})`
    }else if(item.value === 4 ){
      item.label += `(${res.outOfStockCount})`
    }else if(item.value === 5 ){
      item.label += `(${res.shippedCount})`
    }else if(item.value === 6 ){
      item.label += `(${res.signedCount})`
    }else if(item.value === 7 ){
      item.label += `(${res.unsignedCount})`
    }else if(item.value === 8 ){
      item.label += `(${res.exceptionOrderCount})`
    }else if(item.value === 9 ){
      item.label += `(${res.invalidOrderCount})`
    }
    return item
  })
}

/** 查询列表 */
const getList = async () => {
  getStatusAccount()
  if (curMode.value === 'audit' && orderTableRef.value) {
    orderTableRef.value.closeAudit() // 关闭审核建议弹窗
  }
  curMode.value = 'batch'
  loading.value = true
  try {
    // queryParams.value.status = 
    const data = await TradeOrderApi.getOrderPage(queryParams.value)
    list.value = data.list.map((item) => {
      item.selected = false
      item.isExpland = false
      return item
    })
    total.value = data.total
  } finally {
    loading.value = false
  }
}

watch(
  () => [props.status,curStatus],
  () => {
    if(curStatus){
      queryParams.value.status = Number(curStatus)
    }
    //根据状态设置不同的查询条件
    if(props.status === 0 || Number(curStatus) === 0 ) {
      searchList.value =  deepCopy(searchInitList.value).filter((item)=> item.code !== 'validFlag' &&  item.code !=='suggetFlag' && item.code !== 'auditSugget' && item.code !== 'messageFlag' && item.code !== 'unsignedReason'  && item.code !== 'abnormal'  && item.code !== 'invalid')
    }else if(props.status === 1  || Number(curStatus) === 1 ) {
      searchList.value =  deepCopy(searchInitList.value).filter((item)=> item.code !== 'validFlag' && item.code !== 'unsignedReason'  && item.code !== 'abnormal'  && item.code !== 'invalid')
    }else if(props.status === 2  || Number(curStatus) === 2 ) {
      searchList.value =  deepCopy(searchInitList.value).filter((item)=> item.code !== 'source' && item.code !== 'validFlag' && item.code !== 'messageFlag' && item.code !== 'unsignedReason'  && item.code !== 'abnormal'  && item.code !== 'invalid')
    }else if(props.status === 3 || props.status === 4 || props.status === 5 || Number(curStatus) === 3 || Number(curStatus) === 4 || Number(curStatus) === 5) {
      searchList.value =  deepCopy(searchInitList.value).filter((item)=> item.code !== 'validFlag' && item.code !=='suggetFlag' && item.code !== 'auditSugget' && item.code !== 'messageFlag' && item.code !== 'unsignedReason'  && item.code !== 'abnormal'  && item.code !== 'invalid')
    }else if(props.status === 6  || Number(curStatus) === 6 ) {
      searchList.value =  deepCopy(searchInitList.value).filter((item)=> item.code !== 'validFlag' &&  item.code !=='suggetFlag' && item.code !== 'auditSugget' && item.code !== 'messageFlag'  && item.code !== 'abnormal'  && item.code !== 'invalid')
    }else if(props.status === 8  || Number(curStatus) === 8 ) {
      searchList.value =  deepCopy(searchInitList.value).filter((item)=> item.code !== 'validFlag' &&  item.code !=='suggetFlag' && item.code !== 'auditSugget' && item.code !== 'messageFlag'  && item.code !== 'unsignedReason'  && item.code !== 'invalid')
    }else if(props.status === 9  || Number(curStatus) === 9 ) {
      searchList.value =  deepCopy(searchInitList.value).filter((item)=> item.code !== 'validFlag' &&  item.code !=='suggetFlag' && item.code !== 'auditSugget' && item.code !== 'messageFlag' && item.code !== 'unsignedReason'  && item.code !== 'abnormal' )
    }
    if (queryParams.value) {
      queryParams.value.status = props.status
      getList()
    }
  },
  {
    immediate: true
  }
)

/** 搜索按钮操作 */
const handleQuery = async () => {
  queryParams.value.pageNo = 1
  await getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields()
  let status = queryParams.value.status
  queryParams.value = {
    ...initQueryParams,
    status
  }
  handleQuery()
}

/** 查看订单详情 */
const openDetail = (id: number) => {
  push({ name: 'TradeOrderDetail', params: { id } })
}

/** 操作分发 */
const deliveryFormRef = ref()
const updateRemarkForm = ref()
const handleCommand = (command: string, row: TradeOrderApi.OrderVO) => {
  switch (command) {
    case 'remark':
      updateRemarkForm.value?.open(row)
      break
    case 'delivery':
      deliveryFormRef.value?.open(row)
      break
  }
}

// 监听路由变化更新列表，解决订单保存/更新后，列表不刷新的问题。
watch(
  () => currentRoute.value,
  () => {
    getList()
  }
)

// const radio1 = ref(0)

/**
 * 获取提示窗点击结果,
 * 仅为文本提示时，确认后val 为true
 * 带有其他表单元素时,val为undefined,需要手动获取表单值
 */
const getConfirmValue = (val) => {
  // console.log(val, 'val')
  // console.log(radio1.value, 'radio1')
}

const handleOrderStatus = (status: number) => {
  //获取指定订单状态
  queryParams.value = {
    ...initQueryParams,
    status: status
  }
  getSearchMenu(status)
  getList()
}

const pickUpStoreList = ref<PickUpStoreApi.DeliveryPickUpStoreVO[]>([]) // 自提门店精简列表
const deliveryExpressList = ref<DeliveryExpressApi.DeliveryExpressVO[]>([]) // 物流公司

const getSearchMenu = (status) => {
  //根据状态设置不同的查询条件
  if(status === 0 ) {
      searchList.value =  deepCopy(searchInitList.value).filter((item)=> item.code !== 'validFlag' &&  item.code !=='suggetFlag' && item.code !== 'auditSugget' && item.code !== 'messageFlag' && item.code !== 'unsignedReason'  && item.code !== 'abnormal'  && item.code !== 'invalid')
    }else if(status === 1) {
      searchList.value =  deepCopy(searchInitList.value).filter((item)=> item.code !== 'validFlag' && item.code !== 'unsignedReason'  && item.code !== 'abnormal'  && item.code !== 'invalid')
    }else if(status === 2) {
      searchList.value =  deepCopy(searchInitList.value).filter((item)=> item.code !== 'source' && item.code !== 'validFlag' && item.code !== 'messageFlag' && item.code !== 'unsignedReason'  && item.code !== 'abnormal'  && item.code !== 'invalid')
    }else if(status === 3 || status === 4 || status === 5) {
      searchList.value =  deepCopy(searchInitList.value).filter((item)=> item.code !== 'validFlag' && item.code !=='suggetFlag' && item.code !== 'auditSugget' && item.code !== 'messageFlag' && item.code !== 'unsignedReason'  && item.code !== 'abnormal'  && item.code !== 'invalid')
    }else if(status === 6) {
      searchList.value =  deepCopy(searchInitList.value).filter((item)=> item.code !== 'validFlag' &&  item.code !=='suggetFlag' && item.code !== 'auditSugget' && item.code !== 'messageFlag'  && item.code !== 'abnormal'  && item.code !== 'invalid')
    }else if(status === 8) {
      searchList.value =  deepCopy(searchInitList.value).filter((item)=> item.code !== 'validFlag' &&  item.code !=='suggetFlag' && item.code !== 'auditSugget' && item.code !== 'messageFlag'  && item.code !== 'unsignedReason'  && item.code !== 'invalid')
    }else if(status === 9) {
      searchList.value =  deepCopy(searchInitList.value).filter((item)=> item.code !== 'validFlag' &&  item.code !=='suggetFlag' && item.code !== 'auditSugget' && item.code !== 'messageFlag' && item.code !== 'unsignedReason'  && item.code !== 'abnormal' )
    }
}


/**
 * 获取用户选中的行数据
 * curMode 控制按钮事件筛选源
 */
const handleSelectionChange = (val: any) => {
  if (selectedRows.value && selectedRows.value.length > 1) {
    curMode.value = 'batch'
  }
  selectedRows.value = val
}

/**单行数据操作
 * curMode 控制按钮事件筛选源
 */
const showActionDialog = (actionName) => {
  curMode.value = 'single'
  if (batchActionRef.value) {
    nextTick(() => {
      batchActionRef.value.batchActions(actionName)
    })
  }
}
/**
 * 审核建议表数据操作
 */
const updateOrderStatus = (value: any, actionName: string) => {
  curMode.value = 'audit'
  if (batchActionRef.value) {
    selectedRows.value = value
    nextTick(() => {
      batchActionRef.value.batchActions(actionName)
    })
  }
}

/**
 * 清空审核建议表数据
 */
const clearAuditSelect = () => {
  selectedRows.value = []
}

/** 导出按钮操作 */
const handleExport = async () => {
  exportDrawerRef.value?.show()
  // try {
  //   // 导出的二次确认
  //   await message.exportConfirm()
  //   // 发起导出
  //   loadStart()
  //   const data = await TradeOrderApi.exportOrderExcel(queryParams.value)
  //   download.excel(data, '订单列表.xls')
  // } catch {
  // } finally {
  //   loadDone()
  // }
}

const init = async () => {
  const [depatRes, areaRes] = await Promise.all([
    getSimpleDeptList(),
    getGlobeState({ pageNum: 1, pageSize: 100 })
  ])
  depatList.value = buildTree(depatRes)
  searchList.value.map((item) => {
    if (item.code === 'deptId') {
      item.options = depatList.value
    }
  })
  areaList.value = areaRes.map((item) => {
    return {
      label: item.stateName,
      value: item.id
    }
  })
  searchList.value.map((item) => {
    if (item.code === 'areaId') {
      item.options = areaList.value
    }
  })
 

}


/** 初始化 **/
onMounted(async () => {
  getStatusAccount()
  init()
  if(curStatus) queryParams.value.status = Number(curStatus)
  await getList()
  pickUpStoreList.value = await PickUpStoreApi.getSimpleDeliveryPickUpStoreList()
  deliveryExpressList.value = await DeliveryExpressApi.getSimpleDeliveryExpressList()
 
})

const updateSortType = async (val: 'DESC' | 'ASC') => {
  orderSortType.value = val
  queryParams.value.sort = orderSortType.value
  await getList()
}

const spanMethod = ({ row, column, rowIndex, columnIndex }) => {
  // 合并第一列的单元格
  if (columnIndex === 7) {
    return [1, 1] // 第一列合并所有行
  }
  return [1, 1] // 其他列正常显示
}
</script>
<style lang="scss" scoped>
:deep(.subTable .el-table__inner-wrapper::before) {
  height: 0px !important;
}

:deep(.subTable .el-table td.el-table__cell) {
  border-bottom: 0px !important;
}

:deep(.el-table tr.tableRow) {
  background-color: #fff;
  position: relative !important;
  padding-top: 30px !important;
  height: 100px;
}

:deep(.el-table td.btnColumn) {
  z-index: 9 !important;
}

:deep(.el-table--enable-row-hover .el-table__body tr:hover > td.el-table__cell) {
  background-color: #fff;
}

:deep(.el-table .el-table__cell.mergeRow) {
  position: absolute;
  width: 100%;
  left: 0px;
  top: 0;
  padding-left: 52px;
  background-color: transparent;
  border-bottom: 0px !important;
  z-index: 9;
  background-color: #fbfbfd;
  padding-top: 0;
  padding-bottom: 0;
}
</style>
